package cn.com.allunion.sms.service.impl;

import cn.com.allunion.common.DateModule;
import cn.com.allunion.sms.service.SMSRecordService;
import com.cn.dao.util.HibernateDAO;
import com.cn.dao.util.Page;
import com.cn.entity.*;
import org.hibernate.criterion.Conjunction;
import org.hibernate.criterion.Criterion;
import org.hibernate.criterion.Order;
import org.hibernate.criterion.Restrictions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * 业务逻辑实现类
 * Created by YangJie on 2016/4/13.
 */
@Service
public class SMSRecordServiceImpl implements SMSRecordService {
    private static final Logger LOGGER = LoggerFactory.getLogger(SMSRecordServiceImpl.class) ;

    /**
     * 页面大小
     */
    @Value("${pagesize}")
    int pagesize;

    @Autowired
    HibernateDAO hibernateDao;

    @Autowired
    DateModule dateModule ;

    /**
     * 根据下面八个条件进行查询
     *
     * @param userid      用户ID
     * @param operatorId  运营商ID
     * @param startDate   开始时间
     * @param endDate     结束时间
     * @param sendNumber  发送号码
     * @param businessId  业务id
     * @param sendState   状态
     * @param pageCurrent 当前页
     * @return 记录列表
     */
    @Transactional(readOnly = true, rollbackForClassName = "Exception")
    public Page<SMSRecord> findByCriteria(String userid, String operatorId,
                                          Date startDate, Date endDate, String sendNumber, String businessId,
                                          String sendState, int pageCurrent) {
        UserBase ub = hibernateDao.listById(UserBase.class, userid, true);

        List<UserBase_SMSBusiness> list_ubs = hibernateDao.listByCriteria(
                UserBase_SMSBusiness.class, Restrictions.eq("userBase", ub),
                true);
        if (list_ubs != null && list_ubs.size() != 0) {
            Conjunction conj = Restrictions.conjunction();
            List<SMSBusiness> list_sms = new ArrayList<SMSBusiness>();
            for (UserBase_SMSBusiness ubs : list_ubs) {
                list_sms.add(ubs.getSmsBusiness());
            }
            if (operatorId != null && !operatorId.equals("")) {
                SMSOperator smsOperator = hibernateDao.listById(
                        SMSOperator.class, operatorId, true);
                conj.add(Restrictions.eq("smsOperator", smsOperator));
            }

            if (startDate != null && endDate != null) {

                Criterion c1 = Restrictions.ge("createDate",
                        dateModule.getDayBegin(startDate));
                Criterion c2 = Restrictions.lt("createDate",
                        dateModule.getDayEnd(endDate));

                conj.add(c1);
                conj.add(c2);
            }

            if (sendNumber != null && !sendNumber.equals("")) {
                conj.add(Restrictions.eq("sendNumber", sendNumber));
            }

            if (businessId != null && !businessId.equals("")) {
                SMSBusiness smsBusiness = hibernateDao.listById(
                        SMSBusiness.class, businessId, true);
                conj.add(Restrictions.eq("businessRecord", smsBusiness));
            } else {
                conj.add(Restrictions.in("businessRecord", list_sms));
            }

            if (sendState != null && !sendState.equals("")) {
                conj.add(Restrictions.eq("sendState", sendState));
            }

            int allcount = hibernateDao.countByCriteria(SMSRecord.class, conj,
                    false);

            int lastPage = lastPage(allcount, pagesize);
            if (lastPage < pageCurrent) {
                pageCurrent = lastPage;
            }
            if (lastPage <= 1) {
                pageCurrent = 0;
            }
            List<SMSRecord> list = this.hibernateDao.listByPageByOrderCriteria(
                    SMSRecord.class, conj, pagesize, pageCurrent, Order.desc("createDate"), true);
            // return list;

            Page<SMSRecord> page = new Page<SMSRecord>();
            page.setList(list);
            page.setTotal(allcount);
            page.setPageSize(pagesize);
            page.setPageTotal(lastPage);
            return page;
        } else {
            return null;
        }
    }

    /**
     * 相对位置
     *
     * @param count    页数
     * @param pageSize 页面大小
     * @return 相对位置
     */
    public int lastPage(int count, int pageSize) {
        if (count % pageSize == 0) {
            return count / pageSize;
        }

        return count / pageSize + 1;
    }

    public int getPagesize() {
        return pagesize;
    }

    public void setPagesize(int pagesize) {
        this.pagesize = pagesize;
    }

    /**
     * 添加业务
     *
     * @param smsRecord 短信记录
     * @return 方法执行状态
     */
    @Transactional(rollbackForClassName = "Exception")
    public String addNewRecord(SMSRecord smsRecord) {

        if (hibernateDao.saveOrUpdate(smsRecord).equals("success")) {
            return "success";
        } else {
            return "failure";
        }
    }

    /**
     * 根据运营商id和运营商消息唯一识别码查询发送记录
     *
     * @param smsOperatorId     运营商id
     * @param operatorMessageID 运营商消息唯一识别码
     * @return 发送记录
     */
    @Transactional(readOnly = true)
    public List<SMSRecord> findByIdAndObject(String smsOperatorId,
                                             String operatorMessageID) {
        SMSOperator sMsOperator = hibernateDao.listById(SMSOperator.class,
                smsOperatorId, true);
        if (sMsOperator != null) {
            return hibernateDao.listByCriteria(
                    SMSRecord.class,
                    Restrictions.and(
                            Restrictions.eq("smsOperator", sMsOperator)).add(
                            Restrictions.eq("operatorMessageID",
                                    operatorMessageID)), true);
        }
        return null;
    }

    /**
     * 获取记录Id，获取整个对象，修改operatorMessageID
     */
    @Transactional(rollbackForClassName = "Exception")
    public String updateOperatorMessageID(String recordID,
                                          String operatorMessageID, String states) {

        // String sql =
        // "UPDATE SMSRecord SET operatorMessageID = '"+operatorMessageID+"',sendState = '"+states+"' WHERE smsRecordID='"+recordID+"'";
        // int i = hibernateDao.saveOrUpdateBySQL(sql);

        SMSRecord sr = hibernateDao.listById(SMSRecord.class, recordID, true);
        sr.setOperatorMessageID(operatorMessageID);
        sr.setSendState(states);
        String result = hibernateDao.saveOrUpdate(sr);

        return result;
    }

//	/**
//	 * 根据smsRecordID修改states
//	 */
//	public String updateSendState(String smsRecordID,String states) {
//		SMSRecord msr = hibernateDao.listById(SMSRecord.class, smsRecordID,
//				true);
//		if (msr != null ) {
//			msr.setSendState(states);
//			return hibernateDao.saveOrUpdate(msr);
//		}
//		return "false";
//
//	}

    /**
     * 根据 operatorMessageID 和 operateid 修改 states
     */
    @Transactional(rollbackForClassName = "Exception")
    public String updateSendState(String operatorMessageID,
                                  String states, String sendNumber) {
        LOGGER.debug("数据库修改添加检测到operatorMessageID：" + operatorMessageID);
        SMSRecord sr = hibernateDao.listByCriteria(
                SMSRecord.class,
                Restrictions
                        .and(Restrictions.eq("operatorMessageID",
                                operatorMessageID))
                        .add(Restrictions.eq("sendNumber", sendNumber)), true).get(0);
        LOGGER.debug("查出数据库SMSRecord是否为空：" + (sr == null));
        if (sr != null) {
            sr.setSendState(states);
            sr.setUpdateDate(new Date());
            hibernateDao.saveOrUpdate(sr);
            LOGGER.debug("状态修改成功");
            return "success";
        } else {
            LOGGER.debug("状态修改失败-----------SMSRecord查出为NUll");
        }
        return "false";
    }

//	/**
//	 * 根据 operatorMessageID 和 operateid 修改 states
//	 */
//	@Transactional(rollbackForClassName = "Exception")
//	public String updateSendState(String operateid, String operatorMessageID,
//			String states, String sendNumber) {
//
//		SMSOperator so = hibernateDao.listById(SMSOperator.class, operateid,
//				true);
//		List<SMSRecord> list = hibernateDao.listByCriteria(
//				SMSRecord.class,
//				Restrictions
//						.and(Restrictions.eq("operatorMessageID",
//								operatorMessageID))
//						.add(Restrictions.eq("smsOperator", so))
//						.add(Restrictions.eq("sendNumber", sendNumber)), true);
//		if (list != null && list.size() != 0) {
//			SMSRecord sr = list.get(0);
//			sr.setSendState(states);
//			return hibernateDao.saveOrUpdate(sr);
//		}
//		return "false";
//		// String sql =
//		// "UPDATE SMSRecord SET sendState = '"+states+"'where operatorMessageID='"+operatorMessageID+"'and smsOperator.smsOperatorID='"+operateid+"'";
//		// int i = hibernateDao.saveOrUpdateBySQL(sql);
//		// return i;
//	}
}
